layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func', 'laydate', 'upload', 'element', 'tree', 'ztree', 'util'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var upload = layui.upload;
    var element = layui.element;
    var tree = layui.tree;
    var ztree = layui.ztree;
    var util = layui.util


    laydate.render({
        elem: '#timeLimit',
        range: true,
        trigger: 'click',
        //max: Feng.currentDate()
    });
    var Notice = {
        tableId: "noticeTable", //表格id
    };

    //初始化日期
    function format(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    var dateFirst = new Date();
    dateFirst.setDate(1);
    var firstDay = format('yyyy-MM-dd', dateFirst);
    var times = new Date();
    var today = format('yyyy-MM-dd', times);
    var dateStr = firstDay + " - " + today;
    $('#timeLimit').val(dateStr);

    // 刷新表格
    Notice.onClickShop = function (obj) {
        let shopTreeId = obj.data.id;
        var languageAjax = new $ax(Feng.ctxPath + "/btyShopTree/getOneById?shopId=" + shopTreeId);
        var languageResult = languageAjax.start();
        //只有点击的是门店数据才会触发查询
        if (languageResult != null && languageResult != "" && languageResult != undefined) {
            //门店名重新赋值
            $('#dm').val(languageResult.shopCode);
            form.render('select');
            Notice.search(languageResult.shopCode);
        }
    };
    // 初始化树
    tree.render({
        elem: '#shop',
        data: getData(),
        onlyIconControl: true,
        showLine: false,
        click: Notice.onClickShop,
    });


    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyShop/selectAll");
    var languageResult = languageAjax.start();
    console.info(languageResult);
    $.each(languageResult, function (index, val) {
        $("#dm").append("<option value='" + val.shopCode + "'>" + val.shopName + "</option>");
    });
    form.render('select');


    //选择品类时，品项显示为该品类下的
    form.on('select(itemTypeCode)', function (data) {
        $("#itemCode").html("");
        $("#itemCode").append("<option value=''>" + "请选择品项"+ "</option>");
        var itemlistAjax = new $ax(Feng.ctxPath + "/itemInterface/itemlist");
        itemlistAjax.set("itemTypeCode", $("#itemTypeCode").find("option:selected").val());
        var itemlistResult = itemlistAjax.start();
        console.info(itemlistResult);
        $.each(itemlistResult, function (index, val) {
            $("#itemCode").append("<option value='" + val.itemCode + "'>" + val.itemName + "</option>");
        });
        form.render('select');
    });


    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox'},
            // {field: 'shopId', sort: true, title: '门店ID'},
            // {field: 'shopCode', sort: true, title: '门店编码'},
            {field: 'shopName', sort: true, title: '门店',width:256},
            {field: 'billBusType', sort: true, title: '业务类型',width:135},
            {field: 'billType', sort: true, title: '单据种类',width:135},
            // {field: 'itemBigClassCode', sort: true, title: '品项大类编号'},
            // {field: 'itemBigClassName', sort: true, title: '品项大类名称'},
            // {field: 'itemAssistNo', sort: true, title: '品项辅助编号'},
            // {field: 'itemSmallClassCode', sort: true, title: '品项类别编号'},
            {field: 'itemSmallClassName', sort: true, title: '品类'},//品项类别名称
            // {field: 'itemId', sort: true, title: '品项ID'},
            {field: 'itemName', sort: true, title: '品项',width:145},//品项名称
            {field: 'busUnit', sort: true, title: '业务单位',width:104},
            {field: 'outBusAmount', sort: true, title: '业务单位出数量',totalRow: true,width:146},
            {field: 'inBusAmount', sort: true, title: '业务单位入库数量',totalRow: true,width:160},
            // {field: 'itemCode', sort: true, title: '品项编号'},
            {field: 'mainUnit', sort: true, title: '主单位',width:93},
            {field: 'outMainAmount', sort: true, title: '主单位出库数量',totalRow: true,width:146},
            {field: 'inMainAmount', sort: true, title: '主单位入库数量',totalRow: true,width:147},
            {field: 'busDate', sort: true, title: '业务日期' ,templet: function (data) {
                    return layui.util.toDateString(data.busDate, "yyyy-MM-dd");
                },width:106},

            {field: 'auditDate', sort: true, title: '审核日期',templet: function (data) {
                    return layui.util.toDateString(data.auditDate, "yyyy-MM-dd");
                },width:106},
            {field: 'createDate', sort: true, title: '创建时间',templet: function (data) {
                    return layui.util.toDateString(data.createDate, "yyyy-MM-dd");
                },width:106},
            {field: 'makeTime', sort: true, title: '生产日期'},


            {field: 'itemSpec', sort: true, title: '品项规格',width:140},
            {field: 'modifyDate', sort: true, title: '修改时间'},
            {field: 'sellTaxes', sort: true, title: '销售/调拨税额'},
            {field: 'itemSign', sort: true, title: ''},
            {field: 'taxMoney', sort: true, title: ''},
            {field: 'storeBillDtid', hide: true, title: ''},
            {field: 'storeName', sort: true, title: ''},
            {field: 'outStoreMoney', sort: true, title: '出库金额'},
            {field: 'storeBillidRemark', sort: true, title: ''},
            {field: 'billNo', sort: true, title: '单据系统单号'},
            {field: 'arriveMoney', sort: true, title: ''},
            {field: 'storeCode', sort: true, title: ''},
            {field: 'storeBillRemark', sort: true, title: ''},
            {field: 'otherSideName', sort: true, title: '对方机构名称'},
            {field: 'outputRate', sort: true, title: ''},
            {field: 'sysBatchCode', sort: true, title: '系统批次号'},
            {field: 'giftFlag', sort: true, title: ''},
            {field: 'storeBillReState', sort: true, title: ''},
            {field: 'busUser', sort: true, title: ''},
            {field: 'taxes', sort: true, title: ''},
            {field: 'batchCode', sort: true, title: ''},
            {field: 'inStoreMoney', sort: true, title: '入库金额'},
            {field: 'isOut', sort: true, title: ''},
            {field: 'processMoney', sort: true, title: ''},
            {field: 'pushOutStoreMoney', sort: true, title: ''},
            {field: 'pushOutStoreAmount', sort: true, title: ''},
            {field: 'storeBillId', sort: true, title: ''},
            {field: 'sellIncludeTaxMoney', sort: true, title: ''},
            {field: 'otherSideType', sort: true, title: ''},
            {field: 'pushInStoreMoney', sort: true, title: ''},
            {field: 'yield', sort: true, title: ''},
            {field: 'arriveAmount', sort: true, title: ''},
            {field: 'otherSideId', sort: true, title: ''},
            {field: 'sellTaxMoney', sort: true, title: ''},
            {field: 'billBusTypeId', sort: true, title: ''},
            {field: 'pushInStoreAmount', sort: true, title: ''},
            {field: 'aPYear', sort: true, title: '会计年'},
            {field: 'saleMoney', sort: true, title: ''},
            {field: 'storeId', sort: true, title: ''},
            {field: 'itemAbc', sort: true, title: ''},
            {field: 'arrivalDate', sort: true, title: ''},
            {field: 'aPMonth', sort: true, title: '会计月'},
            {field: 'otherSideCode', sort: true, title: ''},
            {field: 'includeTaxMoney', sort: true, title: ''},
            {field: 'parentBillNo', sort: true, title: ''}
        ]];
    };



    /**
     * 点击查询按钮
     */
    Notice.search = function (code) {
        var queryData = {};
        let shopCode = $("#dm").val();
        if (code != null) {
            shopCode = code;
        }
        queryData['shopCode'] = shopCode;
        queryData['pl'] = $("#pl").val();
        queryData['itemTypeCode'] = $("#itemTypeCode").find("option:selected").val();
        queryData['itemCode'] = $("#itemCode").find("option:selected").val();
        queryData['billType'] = $("#billType").find("option:selected").val();
        queryData['timeLimit'] = $("#timeLimit").val();

        table.reload(Notice.tableId, {where: queryData});
    };
    //渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/dsstoreBill/list',
        page: true,
        height: "full-98",
        cellMinWidth: 80,
        limit: 20,
        totalRow: true,	//开启合计行
        cols: Notice.initColumn()
    });


    table.on('edit(noticeTable)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        var data = obj.data; //获得当前行数据
        var field = obj.field;

        var thisobj = $(this);

        var slVal = obj.data.sl;
        var date = obj.data.date;

        if (obj.data.sl != null && obj.data.sl != '' && obj.data.sl != undefined &&
            obj.data.warnPrice != null && obj.data.warnPrice != '' && obj.data.warnPrice != undefined) {
            $.ajax({
                url: "dsstoreBill/selectMoney",
                type: "POST",
                dataType: "json",
                data: data,
                async: false,
                success: function (obj) {
                    if (obj == true) {
                        thisobj.parents("tr").css({color: "red"});
                    } else {
                        thisobj.parents("tr").css({color: "black"});
                    }
                }
            })
        }


    });


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });
});

// 获取tree数据
function getData() {
    var data = [];
    $.ajax({
        url: "/btyShopTree/layuiTree",
        type: "post",
        async: false,
        success: function (result) {
            data = result;
        }
    });
    return data;
}

// tree收缩按钮
$(function () {
    var panehHidden = false;
    if ($(this).width() < 769) {
        panehHidden = true;
    }
    $('#myContiner').layout({initClosed: panehHidden, west__size: 260});
});